package com.starhub.api.sys.user.service.impl;

import com.starhub.common.exception.AppException;
import com.starhub.common.sys.user.LoginUser;
import com.starhub.engine.sys.permission.entity.SysPermission;
import com.starhub.engine.sys.role.service.SysUserRoleService;
import com.starhub.engine.sys.user.bean.UserPermission;
import com.starhub.engine.sys.user.entity.SysUser;
import com.starhub.engine.sys.user.service.SysUserService;
import com.starhub.utils.Util;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1.查询用户信息
        SysUser user = sysUserService.selectUserByUserName(username);
        if(Objects.isNull(user)){
            throw new AppException(401,"用户名或密码错误");
        }
        //2.查询用户权限列表
        List<UserPermission> permissions = findByUserid(user.getId());
        return new LoginUser(user, Util.null2String(user.getId()),permissions);
    }

    /**
     * 查询登录用户权限项
     * @param userId
     * @return
     */
    private List<UserPermission> findByUserid(Long userId) {

        List<UserPermission> permissions = new ArrayList<>();
        Set<SysPermission> sysPermissions = sysUserRoleService.getPermissionCodes(userId);
        if(CollectionUtils.isNotEmpty(sysPermissions)){
            for(SysPermission permission : sysPermissions){
                UserPermission userPermission = new UserPermission(permission.getName());
                userPermission.setUserId(Util.null2String(userId));
                userPermission.setCode(permission.getPerCode());
                permissions.add(userPermission);
            }
        }
        return permissions;
    }
}

